﻿import os
import csv
import time
import json
import random
from datetime import datetime
from playwright.sync_api import sync_playwright

CONFIG_FILE = "config.json"

def load_config():
    with open(CONFIG_FILE, "r", encoding="utf-8") as f:
        return json.load(f)

def block_resources(page):
    page.route("**/*", lambda route: route.abort()
               if route.request.resource_type in ["image", "media", "font"]
               else route.continue_())

def ensure_log_writer():
    today = datetime.now().strftime("%Y-%m-%d")
    folder = os.path.join("logs", today)
    os.makedirs(folder, exist_ok=True)
    path = os.path.join(folder, "click_log.csv")
    is_new = not os.path.exists(path)
    f = open(path, "a", newline='', encoding="utf-8")
    writer = csv.writer(f)
    if is_new:
        writer.writerow(["时间", "代理IP", "国家", "目标链接", "跳转链", "第N跳URL", "Referer", "是否异常"])
    return f, writer

def fetch_ip_country(context):
    ip, country = "", ""
    try:
        page = context.new_page()
        page.goto("http://ipinfo.io/json", timeout=10000)
        info = json.loads(page.inner_text("body"))
        ip = info.get("ip", "")
        country = info.get("country", "")
        page.close()
    except:
        pass
    return ip, country

def build_redirect_page(tracking_link, filename="redirect.html"):
    html = f"""<!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>跳转中...</title>
      <script>
        window.onload = function() {{
          setTimeout(function() {{
            location.href = "{tracking_link}";
          }}, 1000);
        }}
      </script>
    </head>
    <body>
      正在跳转，请稍候...
    </body>
    </html>
    """
    with open(filename, "w", encoding="utf-8") as f:
        f.write(html)
    return os.path.abspath(filename)

def simulate_click(playwright, config):
    proxy_url = "http://127.0.0.1:8000"
    ua = random.choice([
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64)...",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)...",
        "Mozilla/5.0 (Linux; Android 10; SM-G970F)..."
    ])

    browser = playwright.chromium.launch(headless=True)
    context = browser.new_context(proxy={"server": proxy_url}, user_agent=ua)
    page = context.new_page()
    block_resources(page)

    ip, country = fetch_ip_country(context)

    jumps, referers, sizes = [], [], []

    def on_request(req):
        if req.is_navigation_request() and req.frame == page.main_frame:
            jumps.append(req.url)
            referers.append(req.headers.get("referer", ""))

    def on_response(res):
        try:
            sizes.append(len(res.body()))
        except:
            pass

    page.on("request", on_request)
    page.on("response", on_response)

    raw_link = config["TRACK_LINK"].replace("{{DATETIME}}", str(int(time.time() * 1000)))
    redirect_level = config.get("REDIRECT_LEVEL", 0)

    # ✅ 构建跳转页面 HTML，并使用 file:// 加载它
    # html_path = build_redirect_page(raw_link)
    html_path = build_redirect_page("https://eclicklink.com/active?l=https%3A%2F%2Fclick.linksynergy.com%2Fdeeplink%3Fid%3DQShei0b3Wgk%26mid%3D3156%26u1%3D578d200ee7ee4c24bc1525e54cb7ba9f%26murl%3Dhttps%253A%252F%252Fwww.champion.com")
    local_page = f"file:///{html_path.replace(os.sep, '/')}"

    pass #print(f"\n📌 开始处理链接: {raw_link}")
    pass #print(f"🌐 当前代理IP: {ip or 'N/A'} | 国家: {country or 'N/A'}")
    pass #print("🕹️ 模拟点击中...")

    start_time = time.time()
    err = ""

    try:
        pass #print("local_page", local_page)
        page.goto(local_page, wait_until="load", timeout=30000)
        _ = page.content()
        pass #print(_)
        page.mouse.move(200, 200)
        page.mouse.click(200, 200)
        page.mouse.wheel(0, 3000)
        page.keyboard.press("Enter")
        time.sleep(5)

        try:
            _ = page.content()
            pass #print(_)
        except:
            pass

        for i in range(5):
            pass #print(f"⏳ 当前URL: {page.url}")
            time.sleep(1)

    except Exception as e:
        err = str(e)

    # ✅ 控制台跳转链输出
    if jumps:
        pass #print("🔁 跳转链：")
        for i, j in enumerate(jumps):
            pass #print(f"[{i+1}] {j}")

    # ✅ 时间 & 流量统计
    end_time = time.time()
    total_sec = round(end_time - start_time, 2)
    total_kb = round(sum(sizes) / 1024, 1)

    target = jumps[-1] if jumps else raw_link
    ref = referers[-1] if referers else ""
    formatted_chain = "\n".join([f"[{i+1}] {j}" for i, j in enumerate(jumps)])

    f, writer = ensure_log_writer()
    writer.writerow([
        datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        ip, country,
        raw_link,
        formatted_chain,
        jumps[redirect_level] if redirect_level < len(jumps) else (jumps[-1] if jumps else raw_link),
        ref,
        "是" if err else "否"
    ])
    f.close()
    context.close()
    browser.close()

    pass #print(f"✅ 跳转完成，最终URL: {target}")
    pass #print(f"📊 总耗时：{total_sec} 秒 | 估算流量：{total_kb} KB")
    pass #print("📝 日志记录完成")

def main():
    config = load_config()
    with sync_playwright() as pw:
        simulate_click(pw, config)

if __name__ == "__main__":
    main()
